import React, { useEffect, useState, useRef } from 'react';
import { View, Text, ActivityIndicator, SafeAreaView, ScrollView, TouchableOpacity, TextInput, Animated, StyleSheet, Image, Dimensions, Modal as RNModal } from 'react-native';
import Header from '../../../../components/Header';
import { getDeviceRepairDetailApi, appraiseRepairApi } from './api';
import { searchProductApi } from '../../DeviceRepair/DeviceRepairDetail/api';
import jiahaoIcon from '../../../../assets/jiahao.png';
import { Toast } from '@ant-design/react-native';

interface DeviceRepairDetailProps {
    id: string;
    onBackPress?: () => void;
    onNavigateToLogin?: () => void;
}

interface CollapsibleSectionProps {
    title: string;
    isExpanded: boolean;
    onToggle: () => void;
    children: React.ReactNode;
    iconSource: any;
}

const CollapsibleSection: React.FC<CollapsibleSectionProps> = ({ title, isExpanded, onToggle, children, iconSource }) => {
    const animatedHeight = useRef(new Animated.Value(0)).current;
    const animatedOpacity = useRef(new Animated.Value(0)).current;
    const arrowRotation = useRef(new Animated.Value(0)).current;

    useEffect(() => {
        if (isExpanded) {
            // 展开动画
            Animated.parallel([
                Animated.timing(animatedHeight, {
                    toValue: 1,
                    duration: 500,
                    useNativeDriver: false,
                }),
                Animated.timing(animatedOpacity, {
                    toValue: 1,
                    duration: 500,
                    useNativeDriver: false,
                }),
                Animated.timing(arrowRotation, {
                    toValue: 1,
                    duration: 500,
                    useNativeDriver: true,
                }),
            ]).start();
        } else {
            // 收起动画
            Animated.parallel([
                Animated.timing(animatedHeight, {
                    toValue: 0,
                    duration: 500,
                    useNativeDriver: false,
                }),
                Animated.timing(animatedOpacity, {
                    toValue: 0,
                    duration: 500,
                    useNativeDriver: false,
                }),
                Animated.timing(arrowRotation, {
                    toValue: 0,
                    duration: 500,
                    useNativeDriver: true,
                }),
            ]).start();
        }
    }, [isExpanded]);

    return (
        <View style={styles.section}>
            <TouchableOpacity style={styles.sectionHeader} onPress={onToggle}>
                <View style={styles.headerLeft}>
                    <Text style={styles.sectionTitle}>{title}</Text>
                    <Text style={styles.asterisk}>*</Text>
                </View>
                <Animated.Image
                    source={require('../../../../assets/xiala.png')}
                    style={[
                        styles.arrowImage,
                        {
                            transform: [{
                                rotate: arrowRotation.interpolate({
                                    inputRange: [0, 1],
                                    outputRange: ['0deg', '180deg']
                                })
                            }]
                        }
                    ]}
                />
            </TouchableOpacity>
            <Animated.View
                style={[
                    styles.sectionContent,
                    {
                        maxHeight: animatedHeight.interpolate({
                            inputRange: [0, 1],
                            outputRange: [0, 800],
                        }),
                        opacity: animatedOpacity,
                        margin: 0,
                        paddingTop: 0,
                        paddingBottom: 0,
                    }
                ]}
            >
                {children}
            </Animated.View>
        </View>
    );
};

const DeviceRepairDetail: React.FC<DeviceRepairDetailProps> = (props) => {
    const id = props.id || (global as any).deviceRepairDetailId;
    const { onBackPress, onNavigateToLogin } = props;
    const [loading, setLoading] = useState(true);
    const [detail, setDetail] = useState<any>(null);
    const [expandedSections, setExpandedSections] = useState({
        report: true,
        diagnosis: false,
        startRepair: false,
        completeRepair: false,
        evaluation: false
    });

    // 流程相关状态
    const [currentStep, setCurrentStep] = useState(1); // 当前步骤，初始值设为1，后续根据state更新
    const [stepData, setStepData] = useState({
        step1: { needExternal: false, solution: '', estimatedTime: '' },
        step2: { diagnosis: '', solution: '', parts: '' },
        step3: { startTime: '', repairPlan: '', materials: '' },
        step4: { completeTime: '', result: '', cost: '' },
        step5: { rating: 5, comment: '' }
    });

    // 评价相关状态
    const [evaluationData, setEvaluationData] = useState({
        checker_result: 0, // 确认结果: 1-满意 2-不满意 3-一般
        error_state: 0,    // 故障状态: 1-未解决 2-解决
    });

    // 1. 备品备件相关state
    const [selectedProducts, setSelectedProducts] = useState<any[]>([]);
    const [productModalVisible, setProductModalVisible] = useState(false);
    const [productSearch, setProductSearch] = useState('');
    const [productList, setProductList] = useState<any[]>([]);
    const [productLoading, setProductLoading] = useState(false);

    // 状态映射
    const REPAIR_STATE_MAP: { [key: number]: string } = {
        1: '待诊断',
        2: '已诊断',
        3: '维修中',
        4: '待评价',
        5: '已评价',
    };

    // 状态到步骤的映射
    const STATE_TO_STEP_MAP: { [key: number]: number } = {
        1: 2, // 待诊断 -> 故障诊断步骤
        2: 3, // 已诊断 -> 开始维修步骤
        3: 4, // 维修中 -> 完成维修步骤
        4: 5, // 待评价 -> 维修评价步骤
        5: 5, // 已评价 -> 维修评价步骤（已完成）
    };

    // 根据状态获取步骤状态
    const getStepStatus = (stepId: number, currentState: number) => {
        const currentStepId = STATE_TO_STEP_MAP[currentState] || 1;

        if (stepId < currentStepId) {
            return 'completed';
        } else if (stepId === currentStepId) {
            return 'current';
        } else {
            return 'pending';
        }
    };

    // 动态生成流程步骤
    const getSteps = (currentState: number) => [
        { id: 1, title: '故障报修', status: getStepStatus(1, currentState) },
        { id: 2, title: '故障诊断', status: getStepStatus(2, currentState) },
        { id: 3, title: '开始维修', status: getStepStatus(3, currentState) },
        { id: 4, title: '完成维修', status: getStepStatus(4, currentState) },
        { id: 5, title: '维修评价', status: getStepStatus(5, currentState) }
    ];

    // 获取状态样式
    const getStatusStyle = (state: number) => {
        switch (state) {
            case 1: // 待诊断 - 橙色
                return {
                    ...styles.statusText,
                    color: '#ff6600',
                    backgroundColor: '#fff3e0',
                    borderColor: '#ff6600',
                };
            case 2: // 已诊断 - 绿色
                return {
                    ...styles.statusText,
                    color: '#00aa00',
                    backgroundColor: '#e8f5e8',
                    borderColor: '#00aa00',
                };
            case 3: // 维修中 - 红色
                return {
                    ...styles.statusText,
                    color: '#ff4444',
                    backgroundColor: '#ffebee',
                    borderColor: '#ff4444',
                };
            case 4: // 待评价 - 橙色
                return {
                    ...styles.statusText,
                    color: '#ff6600',
                    backgroundColor: '#fff3e0',
                    borderColor: '#ff6600',
                };
            case 5: // 已评价 - 绿色
                return {
                    ...styles.statusText,
                    color: '#00aa00',
                    backgroundColor: '#e8f5e8',
                    borderColor: '#00aa00',
                };
            default:
                return {
                    ...styles.statusText,
                    color: '#888888',
                    backgroundColor: '#f5f5f5',
                    borderColor: '#888888',
                };
        }
    };

    // 处理步骤点击
    const handleStepClick = (stepId: number) => {
        console.log(`点击步骤 ${stepId}，当前步骤: ${currentStep}`);
        setCurrentStep(stepId);
        console.log(`设置步骤为: ${stepId}`);
    };

    // 处理步骤提交
    const handleStepSubmit = (stepId: number) => {
        console.log(`提交步骤 ${stepId} 的数据:`, stepData[`step${stepId}` as keyof typeof stepData]);

        // 这里可以调用相应的API接口
        // 目前只是打印数据

        // 模拟提交成功，进入下一步
        if (stepId < 5) {
            setCurrentStep(stepId + 1);
        }
    };

    // 处理评价选项变化
    const handleEvaluationChange = (field: 'checker_result' | 'error_state', value: number) => {
        setEvaluationData(prev => ({
            ...prev,
            [field]: value
        }));
        console.log(`评价选项变化: ${field} = ${value}`);
    };

    // 处理评价提交
    const handleEvaluationSubmit = async () => {
        console.log('提交评价数据:', {
            id: id,
            checker_result: evaluationData.checker_result,
            error_state: evaluationData.error_state
        });

        try {
            const result = await appraiseRepairApi({
                id: id,
                checker_result: evaluationData.checker_result,
                error_state: evaluationData.error_state
            });

            console.log('评价提交成功:', result);
            Toast.info(result.msg || '评价提交成功', 1);

            // 提交成功后刷新详情数据
            const detailRes = await getDeviceRepairDetailApi(id);
            setDetail(detailRes?.data || null);

            // 跳转到下一个步骤（如果还有的话）
            if (detailRes?.data?.state) {
                const targetStep = STATE_TO_STEP_MAP[detailRes.data.state] || 5;
                setCurrentStep(targetStep);
                console.log(`评价提交后，根据状态 ${detailRes.data.state} 设置当前步骤为: ${targetStep}`);
            }
        } catch (error) {
            console.error('评价提交失败:', error);
            Toast.fail('评价提交失败，请重试', 1);
        }
    };

    // 图片预览相关
    const [imageModalVisible, setImageModalVisible] = useState(false);
    const [selectedImage, setSelectedImage] = useState<string>('');
    const screenWidth = Dimensions.get('window').width;
    const screenHeight = Dimensions.get('window').height;
    // 占位图样式参考DeviceRepairDetail/index.tsx
    const placeholderContainerStyle = {
        width: 120,
        height: 120,
        borderRadius: 8,
        backgroundColor: '#e0e0e0',
        justifyContent: 'center' as const,
        alignItems: 'center' as const,
        overflow: 'hidden' as const,
    };

    // 2. 查询备品备件列表
    const fetchProductList = async (keyword = '') => {
        setProductLoading(true);
        try {
            const params = { current: 1, size: 20, keyword };
            const res = await searchProductApi(params);
            setProductList(res?.data?.records || []);
        } catch (e) {
            setProductList([]);
        } finally {
            setProductLoading(false);
        }
    };
    // 3. 选择/数量调整/删除
    const handleSelectProduct = (item: any) => {
        const exist = selectedProducts.find((p: any) => p.id === item.id);
        if (!exist) {
            setSelectedProducts([...selectedProducts, { ...item, quantity: 1 }]);
        }
        setProductModalVisible(false);
        setProductSearch('');
    };
    const handleProductQuantityChange = (id: string, delta: number) => {
        setSelectedProducts(prev => prev.map(p => p.id === id ? { ...p, quantity: Math.max(1, (p.quantity || 1) + delta) } : p));
    };
    const handleRemoveProduct = (id: string) => {
        setSelectedProducts(prev => prev.filter(p => p.id !== id));
    };

    useEffect(() => {
        const fetchDetail = async () => {
            try {
                const res = await getDeviceRepairDetailApi(id);
                setDetail(res?.data || null);
                console.log('设备报修详情接口返回:', res);

                // 根据state设置当前步骤
                if (res?.data?.state) {
                    const targetStep = STATE_TO_STEP_MAP[res.data.state] || 1;
                    setCurrentStep(targetStep);
                    console.log(`根据状态 ${res.data.state} 设置当前步骤为: ${targetStep}`);
                }

                // 初始化评价数据
                if (res?.data) {
                    setEvaluationData({
                        checker_result: res.data.checker_result || 0,
                        error_state: res.data.error_state || 0,
                    });
                    // 新增：同步 product_list 到 selectedProducts
                    setSelectedProducts(
                        Array.isArray(res.data.product_list)
                            ? res.data.product_list.map((item: any) => ({
                                ...item,
                                id: item.product_id || item.id, // 兼容接口返回
                                quantity: item.quantity || 1,
                                product_name: item.product_name || item.name,
                            }))
                            : []
                    );
                }
            } catch (e) {
                setDetail(null);
            } finally {
                setLoading(false);
            }
        };
        fetchDetail();
    }, [id]);

    const toggleSection = (section: keyof typeof expandedSections) => {
        setExpandedSections(prev => {
            // 如果当前section已经展开，则收起它
            if (prev[section]) {
                return {
                    ...prev,
                    [section]: false
                };
            }
            // 如果当前section未展开，则先收起所有section，再展开当前section
            const newState = {
                report: false,
                diagnosis: false,
                startRepair: false,
                completeRepair: false,
                evaluation: false,
            };
            return {
                ...newState,
                [section]: true
            };
        });
    };

    const renderField = (label: string, value: any, isMultiline: boolean = false) => (
        <View style={styles.fieldRow}>
            <Text style={styles.fieldLabel}>{label}</Text>
            {isMultiline ? (
                <View style={styles.multilineContainer}>
                    <TextInput
                        style={styles.multilineInput}
                        multiline
                        placeholder=""
                        value={value || ''}
                        editable={false}
                    />
                </View>
            ) : (
                <Text style={styles.fieldValue}>{value || ''}</Text>
            )}
        </View>
    );

    // 新增：上下布局的字段渲染
    const renderFieldVertical = (label: string, value: any, isMultiline: boolean = false) => (
        <View style={styles.fieldVerticalRow}>
            <Text style={styles.fieldLabelVertical}>{label}</Text>
            <View style={styles.multilineContainerVertical}>
                <TextInput
                    style={styles.multilineInputVertical}
                    multiline={isMultiline}
                    placeholder=""
                    value={value || ''}
                    editable={false}
                />
            </View>
        </View>
    );

    const renderRadioGroup = (title: string, options: string[], selectedValue: any, onSelect: (value: any) => void) => (
        <View style={styles.fieldRow}>
            <Text style={styles.fieldLabel}>{title}</Text>
            <View style={styles.radioContainer}>
                {options.map((option, index) => (
                    <TouchableOpacity
                        key={index}
                        onPress={() => onSelect(option)}
                        style={styles.radioOption}
                    >
                        <View style={[
                            styles.radioButton,
                            selectedValue === option && styles.radioButtonSelected
                        ]}>
                            {selectedValue === option && (
                                <View style={styles.radioButtonInner} />
                            )}
                        </View>
                        <Text style={styles.radioText}>{option}</Text>
                    </TouchableOpacity>
                ))}
            </View>
        </View>
    );

    // 新增：上下布局的单选按钮组
    const renderRadioGroupVertical = (title: string, options: string[], selectedValue: any, onSelect: (value: any) => void) => (
        <View style={styles.fieldVerticalRow}>
            <Text style={styles.fieldLabelVertical}>{title}</Text>
            <View style={styles.radioContainerVertical}>
                {options.map((option, index) => (
                    <TouchableOpacity
                        key={index}
                        onPress={() => onSelect(option)}
                        style={styles.radioOptionVertical}
                    >
                        <View style={[
                            styles.radioButton,
                            selectedValue === option && styles.radioButtonSelected
                        ]}>
                            {selectedValue === option && (
                                <View style={styles.radioButtonInner} />
                            )}
                        </View>
                        <Text style={styles.radioText}>{option}</Text>
                    </TouchableOpacity>
                ))}
            </View>
        </View>
    );

    // 渲染流程进度条
    const renderProgressBar = () => {
        const currentSteps = getSteps(detail?.state || 1);
        return (
            <View style={styles.progressContainer}>
                <View style={styles.progressBar}>
                    {currentSteps.map((step, index) => (
                        <React.Fragment key={step.id}>
                            <TouchableOpacity
                                style={[
                                    styles.stepCard,
                                    step.status === 'completed' && styles.stepCompleted,
                                    step.status === 'current' && styles.stepCurrent,
                                    step.status === 'pending' && styles.stepPending
                                ]}
                                onPress={() => handleStepClick(step.id)}
                            >
                                <View style={styles.stepCardContent}>
                                    <View style={[
                                        styles.stepIcon,
                                        step.status === 'completed' && styles.stepIconCompleted,
                                        step.status === 'current' && styles.stepIconCurrent,
                                        step.status === 'pending' && styles.stepIconPending
                                    ]}>
                                        <Text style={styles.stepIconText}>{step.id}</Text>
                                    </View>
                                    <Text style={[
                                        styles.stepTitle,
                                        step.status === 'current' && styles.stepTitleCurrent,
                                        step.status === 'completed' && styles.stepTitleCompleted
                                    ]}>
                                        {step.title}
                                    </Text>
                                </View>

                            </TouchableOpacity>
                            {index < currentSteps.length - 1 && (
                                <View style={[
                                    styles.stepConnector,
                                    step.status === 'completed' && styles.stepConnectorCompleted
                                ]} />
                            )}
                        </React.Fragment>
                    ))}
                </View>
            </View>
        );
    };

    // 渲染当前步骤内容
    const renderCurrentStepContent = () => {
        console.log(`渲染当前步骤内容，currentStep: ${currentStep}`);
        switch (currentStep) {
            case 1:
                return (
                    <View style={styles.stepContent}>
                        <Text style={styles.stepContentTitle}>当前步骤: 故障报修</Text>
                        <View style={styles.stepForm}>
                            <View style={styles.fieldRow}>
                                <Text style={styles.fieldLabel}>设备编号</Text>
                                <Text style={styles.fieldValue}>{detail?.device_num || '未知'}</Text>
                            </View>
                            <View style={styles.fieldRow}>
                                <Text style={styles.fieldLabel}>紧急程度</Text>
                                <Text style={styles.fieldValue}>{detail?.level === 1 ? '十万火急' : detail?.level === 2 ? '紧急' : detail?.level === 3 ? '一般紧急' : detail?.level === 4 ? '不紧急' : '未知'}</Text>
                            </View>
                            <View style={styles.fieldRow}>
                                <Text style={styles.fieldLabel}>故障描述</Text>
                                <Text style={styles.fieldValue}>{detail?.error_desc || '暂无描述'}</Text>
                            </View>
                            <View style={styles.fieldRow}>
                                <Text style={styles.fieldLabel}>报修图片</Text>
                                <TouchableOpacity
                                    style={styles.imageContainer}
                                    onPress={() => {
                                        setSelectedImage(detail?.device_link ? String(detail.device_link) : '');
                                        setImageModalVisible(true);
                                    }}
                                >
                                    <Image
                                        source={detail?.device_link ? { uri: String(detail.device_link) } : require('../../../../assets/zwtp.png')}
                                        style={styles.repairImage}
                                        resizeMode="contain"
                                    />
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                );
            case 2:
                return (
                    <View style={styles.stepContent}>
                        <Text style={styles.stepContentTitle}>当前步骤: 故障诊断</Text>
                        <View style={styles.stepForm}>
                            <View style={styles.fieldVerticalRow}>
                                <Text style={styles.fieldLabelVertical}>故障原因</Text>
                                <View style={styles.multilineContainerVertical}>
                                    <TextInput
                                        style={styles.multilineInputVertical}
                                        multiline
                                        placeholder="请输入故障原因"
                                        placeholderTextColor="#999"
                                        value={detail?.error_reason || ''}
                                        editable={false}
                                    />
                                </View>
                            </View>
                            <View style={styles.fieldVerticalRow}>
                                <Text style={styles.fieldLabelVertical}>故障诊断和描述</Text>
                                <View style={styles.multilineContainerVertical}>
                                    <TextInput
                                        style={styles.multilineInputVertical}
                                        multiline
                                        placeholder="请输入故障诊断和描述"
                                        placeholderTextColor="#999"
                                        value={detail?.error_diag_desc || ''}
                                        editable={false}
                                    />
                                </View>
                            </View>
                            {/* 备品备件区域 */}
                            <View style={[styles.fieldVerticalRow, { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }]}>
                                <Text style={styles.fieldLabelVertical}>备品备件</Text>
                                {/* <TouchableOpacity onPress={() => { setProductModalVisible(true); fetchProductList(); }}> */}
                                    <Image source={jiahaoIcon} style={{ width: 24, height: 24 }} />
                                {/* </TouchableOpacity> */}
                            </View>
                            {/* 已选备品备件列表 */}
                            {selectedProducts.length > 0 && (
                                <View style={{ marginBottom: 10 }}>
                                    {selectedProducts.map(item => (
                                        <View key={item.id} style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 6 }}>
                                            <Text style={{ flex: 1 }}>{item.supplier_name || item.product_name || item.name}</Text>
                                            <TouchableOpacity onPress={() => handleProductQuantityChange(item.id, -1)} style={{ paddingHorizontal: 8 }}><Text style={{ fontSize: 18 }}>-</Text></TouchableOpacity>
                                            <Text style={{ width: 30, textAlign: 'center' }}>{item.quantity}</Text>
                                            <TouchableOpacity onPress={() => handleProductQuantityChange(item.id, 1)} style={{ paddingHorizontal: 8 }}><Text style={{ fontSize: 18 }}>+</Text></TouchableOpacity>
                                            <TouchableOpacity onPress={() => handleRemoveProduct(item.id)} style={{ paddingHorizontal: 8 }}><Text style={{ color: 'red' }}>删除</Text></TouchableOpacity>
                                        </View>
                                    ))}
                                </View>
                            )}
                        </View>
                        {/* 备品备件选择模态框 */}
                        <RNModal
                            visible={productModalVisible}
                            transparent={true}
                            animationType="slide"
                            onRequestClose={() => setProductModalVisible(false)}
                        >
                            <View style={styles.modalOverlay}>
                                <View style={styles.supplierModal}>
                                    <View style={styles.supplierModalContent}>
                                        {/* 右上角关闭按钮 */}
                                        <TouchableOpacity style={styles.supplierCloseBtn} onPress={() => setProductModalVisible(false)}>
                                            <Image source={require('../../../../assets/xx.png')} style={styles.supplierCloseIcon} />
                                        </TouchableOpacity>
                                        <Text style={styles.supplierModalTitle}>选择备品备件</Text>
                                        <View style={styles.supplierSearchBox}>
                                            <Image source={require('../../../../assets/ss.png')} style={styles.supplierSearchIcon} />
                                            <TextInput
                                                style={styles.supplierSearchInput}
                                                placeholder="请输入关键词搜索"
                                                placeholderTextColor="#999"
                                                value={productSearch}
                                                onChangeText={text => { setProductSearch(text); fetchProductList(text); }}
                                            />
                                        </View>
                                        <ScrollView style={{ flex: 1 }}>
                                            {productLoading ? (
                                                <ActivityIndicator size="small" color="#0076ff" />
                                            ) : (
                                                productList.length > 0 ? productList.map(item => (
                                                    <TouchableOpacity
                                                        key={item.id}
                                                        style={styles.supplierListItem}
                                                        onPress={() => handleSelectProduct(item)}
                                                    >
                                                        <Text style={styles.supplierListItemText}>{item.supplier_name || item.product_name || item.name}</Text>
                                                    </TouchableOpacity>
                                                )) : (
                                                    <Text style={{ textAlign: 'center', color: '#999', marginTop: 20 }}>暂无数据</Text>
                                                )
                                            )}
                                        </ScrollView>
                                    </View>
                                </View>
                            </View>
                        </RNModal>
                    </View>
                );
            case 3:
                return (
                    <View style={styles.stepContent}>
                        <Text style={styles.stepContentTitle}>当前步骤: 开始维修</Text>
                        <View style={styles.stepForm}>
                            <View style={styles.fieldVerticalRow}>
                                <Text style={styles.fieldLabelVertical}>初步解决方案</Text>
                                <View style={styles.multilineContainerVertical}>
                                    <TextInput
                                        style={styles.multilineInputVertical}
                                        multiline
                                        value={detail?.first_solution || ''}
                                        editable={false}
                                    />
                                </View>
                            </View>
                            <View style={styles.fieldRow}>
                                <Text style={styles.fieldLabel}>是否需要外协</Text>
                                <TouchableOpacity
                                    activeOpacity={1}
                                    onPress={() => { /* 如需可编辑可加切换逻辑 */ }}
                                    style={{ marginLeft: 0 }}
                                >
                                    <View style={[
                                        styles.checkbox,
                                        detail?.is_outsource ? { borderColor: '#0076ff', backgroundColor: '#0076ff' } : { borderColor: '#ccc', backgroundColor: '#fff' },
                                        { width: 22, height: 22, borderRadius: 4, borderWidth: 2, justifyContent: 'center', alignItems: 'center' }
                                    ]}>
                                        {detail?.is_outsource && (
                                            <Image source={require('../../../../assets/duihao.png')} style={{ width: 17, height: 17 }} />
                                        )}
                                    </View>
                                </TouchableOpacity>
                            </View>
                            <View style={styles.fieldRow}>
                                <Text style={styles.fieldLabel}>供应商</Text>
                                <Text style={styles.fieldValue}>{detail?.supplier_name || ''}</Text>
                            </View>
                            <View style={styles.fieldRow}>
                                <Text style={styles.fieldLabel}>预计完成维修时间</Text>
                                <View style={styles.timeSelector}>
                                    <Text style={styles.timeText}>{detail?.expect_end_time || ''}</Text>
                                    <Image source={require('../../../../assets/xiala.png')} style={styles.arrowIcon} />
                                </View>
                            </View>
                        </View>
                    </View>
                );
            case 4:
                return (
                    <View style={styles.stepContent}>
                        <Text style={styles.stepContentTitle}>当前步骤: 完成维修</Text>
                        <View style={styles.stepForm}>
                            <View style={styles.fieldVerticalRow}>
                                <Text style={styles.fieldLabelVertical}>最终解决方案</Text>
                                <View style={styles.multilineContainerVertical}>
                                    <TextInput
                                        style={styles.multilineInputVertical}
                                        multiline
                                        value={detail?.final_solution || ''}
                                        editable={false}
                                    />
                                </View>
                            </View>
                            <View style={styles.fieldVerticalRow}>
                                <Text style={styles.fieldLabelVertical}>我方服务费</Text>
                                <View style={styles.multilineContainerVertical}>
                                    <TextInput
                                        style={styles.multilineInputVertical}
                                        multiline
                                        value={
                                            detail?.service_fee !== undefined && detail?.service_fee !== null && detail?.service_fee !== ''
                                                ? Number(detail.service_fee).toFixed(2)
                                                : ''
                                        }
                                        editable={false}
                                        keyboardType="numeric"
                                    />
                                </View>
                            </View>
                            <View style={styles.fieldVerticalRow}>
                                <Text style={styles.fieldLabelVertical}>外协服务费</Text>
                                <View style={styles.multilineContainerVertical}>
                                    <TextInput
                                        style={styles.multilineInputVertical}
                                        multiline
                                        value={
                                            detail?.out_service_fee !== undefined && detail?.out_service_fee !== null && detail?.out_service_fee !== ''
                                                ? Number(detail.out_service_fee).toFixed(2)
                                                : ''
                                        }
                                        editable={false}
                                        keyboardType="numeric"
                                    />
                                </View>
                            </View>
                            <View style={styles.fieldVerticalRow}>
                                <Text style={styles.fieldLabelVertical}>服务方说明</Text>
                                <View style={styles.multilineContainerVertical}>
                                    <TextInput
                                        style={styles.multilineInputVertical}
                                        multiline
                                        value={detail?.service_desc || ''}
                                        editable={false}
                                    />
                                </View>
                            </View>
                            <View style={styles.fieldVerticalRow}>
                                <Text style={styles.fieldLabelVertical}>验收方说明</Text>
                                <View style={styles.multilineContainerVertical}>
                                    <TextInput
                                        style={styles.multilineInputVertical}
                                        multiline
                                        value={detail?.checker_desc || ''}
                                        editable={false}
                                    />
                                </View>
                            </View>
                            <View style={styles.fieldVerticalRow}>
                                <Text style={styles.fieldLabelVertical}>上传图片</Text>
                                <View style={{ flexDirection: 'row', flexWrap: 'wrap', marginTop: 8 }}>
                                    {detail?.repair_link_list && detail.repair_link_list.length > 0 ? detail.repair_link_list.map((img: any, idx: number) => (
                                        <TouchableOpacity
                                            key={idx}
                                            style={{ position: 'relative', marginRight: 10, marginBottom: 10 }}
                                            onPress={() => {
                                                setSelectedImage(img.link);
                                                setImageModalVisible(true);
                                            }}
                                            activeOpacity={0.8}
                                        >
                                            <Image source={{ uri: img.link }} style={{ width: 70, height: 70, borderRadius: 8 }} />
                                        </TouchableOpacity>
                                    )) : (
                                        <Text style={{ color: '#999', fontSize: 14 }}>暂无图片</Text>
                                    )}
                                </View>
                            </View>
                        </View>
                    </View>
                );
            case 5:
                return (
                    <View style={styles.stepContent}>
                        <Text style={styles.stepContentTitle}>当前步骤: 维修评价</Text>
                        <View style={styles.stepForm}>
                            <View style={styles.evaluationSection}>
                                <Text style={styles.evaluationTitle}>确认结果</Text>
                                <View style={styles.radioContainer}>
                                    {[1, 2, 3].map(val => (
                                        <TouchableOpacity
                                            key={val}
                                            style={styles.radioOption}
                                            onPress={detail?.state === 4 ? () => handleEvaluationChange('checker_result', val) : undefined}
                                            activeOpacity={detail?.state === 4 ? 0.7 : 1}
                                        >
                                            <View style={[styles.radioButton, evaluationData.checker_result === val && styles.radioButtonSelected]}>
                                                {evaluationData.checker_result === val && <View style={styles.radioButtonInner} />}
                                            </View>
                                            <Text style={styles.radioText}>{val === 1 ? '满意' : val === 2 ? '不满意' : '一般'}</Text>
                                        </TouchableOpacity>
                                    ))}
                                </View>
                            </View>
                            <View style={styles.evaluationSection}>
                                <Text style={styles.evaluationTitle}>故障状态</Text>
                                <View style={styles.radioContainer}>
                                    {[1, 2].map(val => (
                                        <TouchableOpacity
                                            key={val}
                                            style={styles.radioOption}
                                            onPress={detail?.state === 4 ? () => handleEvaluationChange('error_state', val) : undefined}
                                            activeOpacity={detail?.state === 4 ? 0.7 : 1}
                                        >
                                            <View style={[styles.radioButton, evaluationData.error_state === val && styles.radioButtonSelected]}>
                                                {evaluationData.error_state === val && <View style={styles.radioButtonInner} />}
                                            </View>
                                            <Text style={styles.radioText}>{val === 1 ? '未解决' : '已解决'}</Text>
                                        </TouchableOpacity>
                                    ))}
                                </View>
                            </View>
                        </View>
                        {/* 只有待评价状态时显示提交按钮 */}
                        {detail?.state === 4 && (
                            <TouchableOpacity
                                style={styles.submitButton}
                                onPress={() => handleEvaluationSubmit()}
                            >
                                <Text style={styles.submitButtonText}>提交评价</Text>
                            </TouchableOpacity>
                        )}
                    </View>
                );
            default:
                return null;
        }
    };

    if (loading) {
        return (
            <SafeAreaView style={styles.container}>
                <Header
                    title="报修详情"
                    showBackButton={true}
                    onBackPress={onBackPress}
                    onNavigateToLogin={onNavigateToLogin}
                />
                <View style={styles.loadingContainer}>
                    <ActivityIndicator size="large" color="#0076ff" />
                </View>
            </SafeAreaView>
        );
    }

    if (!detail) {
        return (
            <SafeAreaView style={styles.container}>
                <Header
                    title="报修详情"
                    showBackButton={true}
                    onBackPress={onBackPress}
                    onNavigateToLogin={onNavigateToLogin}
                />
                <View style={styles.loadingContainer}>
                    <Text>未获取到详情数据</Text>
                </View>
            </SafeAreaView>
        );
    }

    return (
        <SafeAreaView style={styles.container}>
            <Header
                title="报修详情"
                showBackButton={true}
                onBackPress={onBackPress}
                onNavigateToLogin={onNavigateToLogin}
            />
            <View style={styles.content}>
                {/* 流程进度条 - 固定在顶部 */}
                {renderProgressBar()}

                {/* 当前步骤内容 - 可滚动 */}
                <ScrollView style={styles.scrollContent}>
                    {renderCurrentStepContent()}
                </ScrollView>
            </View>
            {/* 图片全屏预览Modal */}
            <RNModal
                visible={imageModalVisible}
                transparent={true}
                animationType="fade"
                onRequestClose={() => setImageModalVisible(false)}
            >
                <View style={{
                    flex: 1,
                    backgroundColor: 'rgba(0, 0, 0, 0.9)',
                    justifyContent: 'center',
                    alignItems: 'center',
                }}>
                    <TouchableOpacity
                        style={{
                            flex: 1,
                            justifyContent: 'center',
                            alignItems: 'center',
                            width: '100%',
                            height: '100%',
                        }}
                        onPress={() => setImageModalVisible(false)}
                        activeOpacity={1}
                    >
                        <Image
                            source={selectedImage ? { uri: selectedImage } : require('../../../../assets/zwtp.png')}
                            style={{ width: screenWidth * 0.9, height: screenHeight * 0.7, borderRadius: 10 }}
                            resizeMode="contain"
                        />
                    </TouchableOpacity>
                </View>
            </RNModal>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    content: {
        flex: 1,
        padding: 0,
    },
    scrollContent: {
        flex: 1,
    },
    loadingContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    section: {
        backgroundColor: '#f5f5f5',
        marginBottom: 0,
    },
    sectionHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 16,
        borderBottomWidth: 1,
        borderBottomColor: '#f0f0f0',
    },
    headerLeft: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    sectionTitle: {
        fontSize: 16,
        fontWeight: '500',
        color: '#333',
    },
    asterisk: {
        color: '#ff4444',
        fontSize: 16,
        marginLeft: 4,
    },
    arrowIcon: {
        width: 18,
        height: 18,
        marginLeft: 8,
        resizeMode: 'contain',
    },
    arrowImage: {
        width: 16,
        height: 16,
        resizeMode: 'contain',
    },
    sectionContent: {
        padding: 16,
        backgroundColor: '#fff',
    },
    cardContainer: {
        backgroundColor: '#fff',
        padding: 15,
        borderRadius: 8,
    },
    fieldRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 8,
        borderBottomWidth: 1,
        borderBottomColor: '#f0f0f0',
    },
    fieldLabel: {
        fontSize: 14,
        color: '#666',
        flex: 1,
    },
    fieldValue: {
        fontSize: 14,
        color: '#333',
        flex: 1,
        textAlign: 'right',
    },
    multilineContainer: {
        flex: 1,
        marginLeft: 10,
    },
    multilineInput: {
        borderWidth: 1,
        borderColor: '#e0e0e0',
        borderRadius: 8,
        padding: 12,
        minHeight: 80,
        textAlignVertical: 'top',
        backgroundColor: '#fafafa',
        fontSize: 14,
        color: '#333',
    },
    addButton: {
        width: 30,
        height: 30,
        borderRadius: 15,
        justifyContent: 'center',
        alignItems: 'center',
    },
    addButtonImage: {
        width: 24,
        height: 24,
        resizeMode: 'contain',
    },
    checkbox: {
        width: 20,
        height: 20,
        borderWidth: 2,
        borderColor: '#ccc',
        borderRadius: 4,
        backgroundColor: 'transparent',
        marginRight: 0,
        justifyContent: 'center',
        alignItems: 'center',
        // 新增以下属性确保对号居中
        display: 'flex',
    },
    // 流程进度条样式
    progressContainer: {
        backgroundColor: '#fff',
        paddingVertical: 8,
        paddingHorizontal: 16,
        marginBottom: 6,
    },
    progressBar: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    stepCard: {
        flex: 1,
        backgroundColor: '#fff',
        borderRadius: 8,
        paddingVertical: 4,
        paddingHorizontal: 6,
        marginHorizontal: 4,
        alignItems: 'center',
        minHeight: 45,
    },
    stepCompleted: {
        backgroundColor: '#fff',
    },
    stepCurrent: {
        backgroundColor: '#fff',
    },
    stepPending: {
        backgroundColor: '#fff',
    },
    stepCardContent: {
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
    },
    stepIcon: {
        width: 20,
        height: 20,
        borderRadius: 10,
        backgroundColor: '#ccc',
        justifyContent: 'center',
        alignItems: 'center',
        marginBottom: 2,
    },
    stepIconCompleted: {
        backgroundColor: '#4caf50',
    },
    stepIconCurrent: {
        backgroundColor: '#2196f3',
    },
    stepIconPending: {
        backgroundColor: '#ccc',
    },
    stepIconText: {
        color: '#fff',
        fontSize: 10,
        fontWeight: 'bold',
    },
    stepTitle: {
        fontSize: 10,
        color: '#666',
        fontWeight: '500',
    },
    stepTitleCurrent: {
        color: '#2196f3',
        fontWeight: 'bold',
    },
    stepTitleCompleted: {
        color: '#4caf50',
        fontWeight: 'bold',
    },
    stepDescription: {
        fontSize: 10,
        color: '#999',
        textAlign: 'center',
        lineHeight: 12,
    },
    currentStepText: {
        fontSize: 10,
        color: '#2196f3',
        fontWeight: 'bold',
        marginTop: 4,
    },
    stepConnector: {
        flex: 1,
        height: 2,
        backgroundColor: '#ccc',
        marginHorizontal: 4,
    },
    stepConnectorCompleted: {
        backgroundColor: '#4caf50',
    },
    // 当前步骤内容样式
    stepContent: {
        backgroundColor: '#fff',
        paddingVertical: 12,
        paddingHorizontal: 16,
        marginBottom: 6,
        borderRadius: 8,
    },
    stepContentTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 4,
    },
    stepContentDescription: {
        fontSize: 14,
        color: '#666',
        marginBottom: 16,
    },
    stepForm: {
        marginBottom: 16,
    },
    formLabel: {
        fontSize: 14,
        color: '#333',
        marginBottom: 8,
        paddingVertical: 8,
        paddingHorizontal: 12,
        backgroundColor: '#f8f8f8',
        borderRadius: 4,
    },
    submitButton: {
        backgroundColor: '#2196f3',
        borderRadius: 6,
        paddingVertical: 12,
        paddingHorizontal: 20,
        alignItems: 'center',
    },
    submitButtonText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
    },
    checkboxSelected: {
        backgroundColor: '#0076ff',
        borderColor: '#0076ff',
        // 保证对号居中
        justifyContent: 'center',
        alignItems: 'center',
    },
    radioContainer: {
        flex: 1,
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginLeft: 10,
    },
    radioContainerVertical: {
        width: '100%',
        marginTop: 8,
        flexDirection: 'row',
        flexWrap: 'wrap',
    },
    radioOption: {
        flexDirection: 'row',
        alignItems: 'center',
        marginRight: 20,
        marginBottom: 10,
    },
    radioOptionVertical: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 10,
        marginRight: 20,
    },
    radioButton: {
        width: 20,
        height: 20,
        borderRadius: 10,
        borderWidth: 2,
        borderColor: '#ccc',
        backgroundColor: 'transparent',
        marginRight: 8,
        justifyContent: 'center',
        alignItems: 'center',
    },
    radioButtonSelected: {
        borderColor: '#0076ff',
        backgroundColor: '#0076ff',
    },
    radioButtonInner: {
        width: 8,
        height: 8,
        borderRadius: 4,
        backgroundColor: '#fff',
    },
    radioText: {
        fontSize: 14,
        color: '#333',
    },
    // 新增：上下布局样式
    fieldVerticalRow: {
        paddingVertical: 8,
        borderBottomWidth: 1,
        borderBottomColor: '#f0f0f0',
        marginBottom: 0,
    },
    fieldLabelVertical: {
        fontSize: 14,
        color: '#666',
        marginBottom: 8,
    },
    multilineContainerVertical: {
        width: '100%',
    },
    multilineInputVertical: {
        borderWidth: 1,
        borderColor: '#e0e0e0',
        borderRadius: 8,
        padding: 12,
        minHeight: 80,
        textAlignVertical: 'top',
        backgroundColor: '#fafafa',
        fontSize: 14,
        color: '#333',
    },
    statusText: {
        fontSize: 14,
        fontWeight: 'bold',
        paddingHorizontal: 12,
        paddingVertical: 6,
        borderRadius: 4,
        borderWidth: 1,
        textAlign: 'center',
    },
    statusContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#fff',
        padding: 16,
        marginBottom: 10,
    },
    statusLabel: {
        fontSize: 16,
        fontWeight: '500',
        color: '#333',
        marginRight: 8,
    },
    imageContainer: {
        marginTop: 8,
    },
    repairImage: {
        width: 120,
        height: 120,
        borderRadius: 8,
        marginTop: 4,
        backgroundColor: '#f0f0f0',
    },
    checkmark: {
        fontSize: 16,
        color: '#fff',
        fontWeight: 'bold',
        textAlign: 'center',
        lineHeight: 18,
        // 新增以下属性确保对号居中
        textAlignVertical: 'center',
        includeFontPadding: false,
    },
    timeSelector: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        flex: 1,
    },
    timeText: {
        fontSize: 14,
        color: '#333',
        flex: 1,
    },
    placeholderText: {
        fontSize: 14,
        color: '#999',
        fontStyle: 'italic',
        paddingVertical: 12,
        paddingHorizontal: 12,
    },
    evaluationSection: {
        marginBottom: 20,
    },
    evaluationTitle: {
        fontSize: 16,
        fontWeight: '500',
        color: '#333',
        marginBottom: 12,
    },
    // 备品备件模态框样式
    modalOverlay: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'flex-end',
    },
    supplierModal: {
        width: '100%',
        height: '80%',
        backgroundColor: '#fff',
        // borderTopLeftRadius: 10,
        // borderTopRightRadius: 10,
        overflow: 'hidden',
    },
    supplierModalContent: {
        flex: 1,
        backgroundColor: '#fff',
        paddingTop: 20,
        paddingHorizontal: 20,
        paddingBottom: 10,
    },
    supplierCloseBtn: {
        position: 'absolute',
        top: 10,
        right: 10,
        zIndex: 1,
    },
    supplierCloseIcon: {
        width: 24,
        height: 24,
    },
    supplierModalTitle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#333',
        textAlign: 'center',
        marginBottom: 15,
    },
    supplierSearchBox: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#f0f0f0',
        borderRadius: 8,
        paddingHorizontal: 10,
        marginBottom: 15,
    },
    supplierSearchIcon: {
        width: 20,
        height: 20,
        marginRight: 10,
    },
    supplierSearchInput: {
        flex: 1,
        fontSize: 16,
        color: '#333',
    },
    supplierListItem: {
        paddingVertical: 12,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    supplierListItemText: {
        fontSize: 16,
        color: '#333',
    },
});

export default DeviceRepairDetail; 